package com.frxuexi.mynews.activity

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.frxuexi.lib_commom.GlideUtils
import com.frxuexi.mynews.databinding.ItemVideoBinding
import com.frxuexi.mynews.entity.VideoEntity

class VideoAdapter(val context:Context,val list:ArrayList<VideoEntity>):RecyclerView.Adapter<VideoAdapter.VideoViewHolder>() {

    lateinit var itemDB:ItemVideoBinding

    @JvmField
    var onItemClickListener: OnItemClickListener?=null
    @JvmField
    var onItemLongClickListener: OnItemLongClickListener?=null

    inner class VideoViewHolder(view: View):ViewHolder(view){
        var title=itemDB.videoTitle
//        var img=itemDB.videoImg
        var vp=itemDB.videoVp
    }

    fun addData(list:List<VideoEntity>){
        this.list.clear()
        this.list.addAll(list)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        itemDB= ItemVideoBinding.inflate(LayoutInflater.from(context),parent,false)
        return VideoViewHolder(itemDB.root)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        val entity = list.get(position)
        holder.apply {
            title.text=entity.title
//            GlideUtils.loadImage(context,entity.imgurl,img)

            itemView.setOnClickListener {
                onItemClickListener?.onClick(position)
            }
            itemView.setOnLongClickListener {
                onItemLongClickListener?.onLongClick(position)
                true
            }
        }

        holder.vp.apply {
            //延迟播放设置
            setUpLazy(entity.videourl,true,null,null,entity.title)
            titleTextView.visibility=View.GONE
            backButton.visibility=View.GONE
            //防止错位
            playPosition=position

            //自动横竖屏
            isAutoFullWithSize=true

            //音视频焦点是否释放
            isReleaseWhenLossAudio=false

            dismissControlTime=100

            //设置第一项自动播放
            if(position==0){
                startPlayLogic()
            }
        }


    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener){
        this.onItemClickListener=onItemClickListener
    }

    fun setOnItemLongClickListener(onItemLongClickListener: OnItemLongClickListener){
        this.onItemLongClickListener=onItemLongClickListener
    }



    interface OnItemClickListener{
        fun onClick(position: Int)
    }

    interface OnItemLongClickListener{
        fun onLongClick(position: Int)
    }

}